package org.huanletao.ssm.controller;

import org.huanletao.ssm.model.RespBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * </p>
 * package: org.huanletao.webs.controller
 * description:
 * className: FileUploadController
 * author:  踏雪无痕
 * copyright: Copyright (c) 2022/8/25 14:00
 * since: 1.0.0
 */
@Controller
public class CommonController {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    private static final String uploadPath = "/static/upload/";

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("upload")
    @ResponseBody
    public RespBean<String> fileUpload(MultipartFile file, HttpServletRequest request) {

        URL resource = Class.class.getClassLoader().getResource("/");
        String path = resource.getPath();
        System.out.println("path = " + path);

        String format = sdf.format(new Date());
        String realPath = request.getServletContext().getRealPath("/") + uploadPath + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();

        String newFileName = UUID.randomUUID() + oldName.substring(oldName.indexOf("."));

        try {
            file.transferTo(new File(folder, newFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + uploadPath + format + newFileName;
        return RespBean.ok("上传成功", url);
    }
}
